package com.qiaoba.api.auth.utils;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.jwt.JWTUtil;
import com.qiaoba.api.auth.constant.SecurityConstant;
import com.qiaoba.common.base.exception.ServiceException;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * Jwt工具类
 *
 * @author ailanyin
 * @date 2023-09-16 20:33:39
 */
public class JwtUtil extends JWTUtil {

    private static String SECRET_KEY;

    public static void setSecretKey(String secretKey) {
        SECRET_KEY = secretKey;
    }

    /**
     * 12小时
     */
    public static final long EXPIRATION_TIME = 12 * 3600 * 1000;

    public static final String PAYLOAD_USER_ID = "user_id";
    public static final String PAYLOAD_USERNAME = "username";
    public static final String PAYLOAD_DEVICE_SN = "device_sn";
    public static final String PAYLOAD_NICKNAME = "nickname";
    private static final String PAYLOAD_EXPIRE_TIME = "expire_time";

    public static String generateToken(String userId, String username, String deviceSn, String nickname) {
        Map<String, Object> payload = new HashMap<>(16);
        payload.put(PAYLOAD_USER_ID, userId);
        payload.put(PAYLOAD_USERNAME, username);
        payload.put(PAYLOAD_DEVICE_SN, deviceSn);
        payload.put(PAYLOAD_NICKNAME, nickname);
        payload.put(PAYLOAD_EXPIRE_TIME, System.currentTimeMillis() + EXPIRATION_TIME);
        return createToken(payload, SECRET_KEY.getBytes());
    }

    public static Boolean verify(String token) {
        try {
            if (verify(token, SECRET_KEY.getBytes())) {
                Date expireTime = new Date(Long.parseLong(parseToken(token).getPayload(PAYLOAD_EXPIRE_TIME).toString()));
                int compare = DateUtil.compare(expireTime, new Date());
                return compare > 0;
            }
            return false;
        } catch (Exception e) {
            return false;
        }
    }

    public static String getToken(HttpServletRequest request, boolean allowNull) {
        // 取Header中的Token
        String authHeader = request.getHeader(SecurityConstant.TOKEN_HEADER);
        if (StrUtil.isNotBlank(authHeader) && authHeader.startsWith(SecurityConstant.TOKEN_HEAD)) {
            return authHeader.substring(SecurityConstant.TOKEN_HEAD.length());
        }

        if (allowNull) {
            return null;
        }

        throw new ServiceException("Token不存在");
    }

}
